package com.yyfax.demo.watch;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.testng.collections.Lists;

public class Registry {
	
	public static List<WatchEventListener<? extends WatchEvent>> listeners = Lists.newArrayList();
	
	
	public void register(WatchEventListener<? extends WatchEvent> listener){
		listeners.add(listener);
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public <E extends WatchEvent> void pushEvent(E event){
		for(WatchEventListener listener : listeners){
			Type[] params = ((ParameterizedType)(listener.getClass().getGenericInterfaces()[0])).getActualTypeArguments();
			Type type = params[0];
			Class<? extends WatchEvent> cls = (Class<? extends WatchEvent>)type;
			if(event.getClass().isAssignableFrom(cls)){
				listener.doSomething(event);
			}
		}
	}
	
	
	public static void main(String[] args) {
		Registry registry = new Registry();
		registry.register(new EventAListener());
		registry.register(new EventBListener());
		
		registry.pushEvent(new EventA("123"));


	}

}
